package cn.wjx.taobaounion.presenter.impl;

import java.util.ArrayList;
import java.util.List;

import cn.wjx.taobaounion.model.Api;
import cn.wjx.taobaounion.model.domain.Histories;
import cn.wjx.taobaounion.model.domain.SearchRecommend;
import cn.wjx.taobaounion.model.domain.SearchResult;
import cn.wjx.taobaounion.presenter.ISearchPresenter;
import cn.wjx.taobaounion.utils.JsonCacheUtil;
import cn.wjx.taobaounion.utils.LogUtils;
import cn.wjx.taobaounion.utils.RetrofitManager;
import cn.wjx.taobaounion.view.ISearchPageCallback;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static java.net.HttpURLConnection.HTTP_OK;

/**
 * @author WuChangJian
 * @date 2020/6/26 21:07
 */
public class SearchPresenterImpl implements ISearchPresenter {
    private static final int DEFAULT_PAGE = 1;
    private int mCurPage = DEFAULT_PAGE;
    private String mCurKeyWord = null;

    private ISearchPageCallback mCallback;
    private Api mApi;
    private JsonCacheUtil mCacheUtil;

    public SearchPresenterImpl() {
        RetrofitManager instance = RetrofitManager.getInstance();
        Retrofit retrofit = instance.getRetrofit();
        mApi = retrofit.create(Api.class);
        mCacheUtil = JsonCacheUtil.getInstance();
    }
    @Override
    public void getHistories() {
        Histories histories = mCacheUtil.getValue(KEY_HISTORIES, Histories.class);
        if (mCallback != null) {
            mCallback.onHistoriesLoaded(histories);
        }
    }

    public static final String KEY_HISTORIES = "key_histories";
    public static final int DEFAULT_HISTORIES_SIZE = 10;
    private int mHistoriesMaxSize = DEFAULT_HISTORIES_SIZE;
    /**
     * 添加历史记录
     * @param history
     */
    private void saveHistories(String history) {
        // 记录如果已经存在，去重在添加
        // 1. 去重
        Histories histories = mCacheUtil.getValue(KEY_HISTORIES, Histories.class);
        List<String> historiesList = null;
        if (histories != null && histories.getHistories() != null) {
            historiesList = histories.getHistories();
            if (historiesList.contains(history)) {
                historiesList.remove(history);

            }
        }
        // 2. 初始为空实例化
        if (historiesList == null) {
            historiesList = new ArrayList<>();
        }
        if (histories == null) {
            histories = new Histories();
            histories.setHistories(historiesList);
        }
        // 3. 对个数进行限制
        if (historiesList.size() > mHistoriesMaxSize) {
            historiesList = historiesList.subList(0, mHistoriesMaxSize);
        }
        // 4. 添加记录
        historiesList.add(history);
        // 5. 保存记录
        mCacheUtil.saveCache(KEY_HISTORIES, histories);
    }

    @Override
    public void delHistories() {
        mCacheUtil.delCache(KEY_HISTORIES);
        if (mCallback != null) {
            mCallback.onHistoriesDeleted();
        }
    }

    @Override
    public void doSearch(String keyword) {
        if (mCurKeyWord == null || !mCurKeyWord.equals(keyword)) {
            mCurKeyWord = keyword;
            this.saveHistories(keyword);
        }
        if (mCallback != null) {
            mCallback.onLoading();
        }
        Call<SearchResult> task = mApi.getSearchResult(mCurPage, keyword);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code = response.code();
                if (code == HTTP_OK) {
                    if (mCallback != null) {
                        handleSearchResult(response.body());
                    }
                } else {
                    // 请求失败
                    LogUtils.d(SearchPresenterImpl.this, "response code-->" + code);
                    onError();
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
                t.printStackTrace();
                onError();
            }
        });
    }

    private void onError() {
        if (mCallback != null) {
            mCallback.onError();
        }
    }

    private void handleSearchResult(SearchResult body) {
        if (mCallback != null) {
            if (!isResultEmpty(body)) {
                mCallback.onSearchSuccess(body);
            } else {
                mCallback.onEmpty();
            }
        }
    }

    private boolean isResultEmpty(SearchResult body) {
        try {
            return body.getData() == null || body.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data().size() == 0;
        } catch (Exception e) {
            return true;
        }

    }

    @Override
    public void reSearch() {
        this.doSearch(mCurKeyWord);
    }

    @Override
    public void loaderMore() {
        mCurPage++;
        Call<SearchResult> task = mApi.getSearchResult(mCurPage, mCurKeyWord);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code = response.code();
                if (code == HTTP_OK) {
                    if (mCallback != null) {
                        handleLoaderMoreResult(response.body());
                    }
                } else {
                    // 请求失败
                    LogUtils.d(SearchPresenterImpl.this, "response code-->" + code);
                    handleLoaderMoreError();
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
                t.printStackTrace();
                handleLoaderMoreError();
            }
        });
    }

    private void handleLoaderMoreError() {
        mCurPage--;
        if (mCallback != null) {
            mCallback.onLoaderMoreError();
        }
    }

    private void handleLoaderMoreResult(SearchResult body) {
        if (mCallback != null) {
            if (!isResultEmpty(body)) {
                mCallback.onLoaderMore(body);
            } else {
                mCallback.onLoaderMoreEmpty();
            }
        }
    }

    @Override
    public void getRecommendWords() {
        Call<SearchRecommend> task = mApi.getSearchRecommend();
        task.enqueue(new Callback<SearchRecommend>() {
            @Override
            public void onResponse(Call<SearchRecommend> call, Response<SearchRecommend> response) {
                int code = response.code();
                if (code == HTTP_OK) {
                    if (mCallback != null) {
                        SearchRecommend recommend = response.body();
                        mCallback.onRecommendWordsLoaded(recommend.getData());
                    }
                } else {
                    // 请求失败
                    LogUtils.d(SearchPresenterImpl.this, "response code-->" + code);

                }
            }

            @Override
            public void onFailure(Call<SearchRecommend> call, Throwable t) {
                LogUtils.d(SearchPresenterImpl.this, "onFailure-->" + t.getMessage());
            }
        });
    }

    @Override
    public void registerViewCallback(ISearchPageCallback callback) {
        this.mCallback = callback;
    }

    @Override
    public void unregisterViewCallback(ISearchPageCallback callback) {
        if (mCallback != null) {
            mCallback = null;
        }
    }
}
